package servlet;

import entity.Address;
import entity.Cart;
import entity.Order;
import service.CartService;
import service.OrderService;
import service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

@WebServlet("/OrderServlet")
public class OrderServlet extends HttpServlet {
    private OrderService orderService = new OrderService();
    private CartService cartService = new CartService();
    private UserService userService = new UserService();

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HashMap<String,String> user =  (HashMap<String, String>) request.getSession().getAttribute("user");
        if(user==null){
            request.getRequestDispatcher("login.jsp").forward(request,response);
            return;
        }
        int userId = Integer.parseInt(user.get("userId"));// 从会话中获取用户ID
        String roleName = userService.getUserRole(userId);
        System.out.println(roleName);
        // 跳转到订单管理页面
        if (Objects.equals(roleName, "U")) {//用户
            // 获取用户的订单信息
            List<Order> orders = orderService.getOrdersByUserId(userId);

            // 将订单信息传递到JSP页面
            request.setAttribute("orders", orders);
            System.out.println(orders);
            request.getRequestDispatcher("/orderManagement_user.jsp").forward(request, response);
        }else if(Objects.equals(roleName, "D")){//店铺
            // 获取用户的订单信息
            List<Order> orders = orderService.getOrdersByShopUserId(userId);
            // 将订单信息传递到JSP页面
            request.setAttribute("orders", orders);
            request.getRequestDispatcher("/orderManagement_shop.jsp").forward(request, response);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HashMap<String,String> user =  (HashMap<String, String>) request.getSession().getAttribute("user");
        if(user==null){
            response.sendRedirect("login.jsp");
        }
        int userId = Integer.parseInt(user.get("userId"));// 从会话中获取用户ID
        try {
            // 获取购物车中的商品
            List<Cart> cartItems = cartService.getCartItems(userId);
            if (cartItems == null || cartItems.isEmpty()) {
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                response.getWriter().write("{\"status\": \"error\", \"message\": \"购物车为空！\"}");
                return;
            }

            // 获取收货地址
            Address address = cartService.getDefaultAddress(userId);
            if (address == null) {
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                response.getWriter().write("{\"status\": \"error\", \"message\": \"未找到收货地址！\"}");
                return;
            }

            // 计算总价
            double totalPrice = cartService.calculateTotalPrice(cartItems);
            double shippingFee = 5.0; // 假设固定运费
            double payableAmount = totalPrice + shippingFee;

            orderService.createOrder(userId, cartItems, address, payableAmount);

            // 返回成功响应
            response.setStatus(HttpServletResponse.SC_OK);
            response.getWriter().write("{\"status\": \"success\", \"message\": \"订单提交成功！\"}");

        } catch (SQLException e) {
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            response.getWriter().write("{\"status\": \"error\", \"message\": \"服务器错误，请稍后重试！\"}");
        }
    }

    protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String action = request.getParameter("action");
        int orderId = Integer.parseInt(request.getParameter("orderId"));

        if ("cancel".equals(action)) {
            // 取消订单
            boolean success = orderService.updateOrderStatus(orderId, "已取消");

            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            if (success) {
                response.getWriter().write("{\"status\": \"success\", \"message\": \"订单已取消！\"}");
            } else {
                response.getWriter().write("{\"status\": \"error\", \"message\": \"取消订单失败！\"}");
            }
        }
    }

    // 处理确认收货、确认订单、发货请求
    protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String action = request.getParameter("action");
        int orderId = Integer.parseInt(request.getParameter("orderId"));

        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");

        if (action == null || orderId <= 0) {
            response.getWriter().write("{\"status\": \"error\", \"message\": \"无效的请求参数！\"}");
            return;
        }

        boolean success = false;
        String message = "";

        try {
            switch (action) {
                case "confirm":
                    // 确认订单逻辑
                    success = orderService.updateOrderStatus(orderId, "待发货");
                    message = success ? "订单已确认！" : "确认订单失败！";
                    break;

                case "ship":
                    // 发货逻辑
                    success = orderService.updateOrderStatus(orderId, "已发货");
                    message = success ? "订单已发货！" : "发货失败！";
                    break;

                case "receive":
                    // 确认收货逻辑
                    success = orderService.updateOrderStatus(orderId, "已收货");
                    message = success ? "订单已确认收货！" : "确认收货失败！";
                    break;

                default:
                    response.getWriter().write("{\"status\": \"error\", \"message\": \"无效的操作类型！\"}");
                    return;
            }

            // 返回结果
            if (success) {
                response.getWriter().write("{\"status\": \"success\", \"message\": \"" + message + "\"}");
            } else {
                response.getWriter().write("{\"status\": \"error\", \"message\": \"" + message + "\"}");
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().write("{\"status\": \"error\", \"message\": \"服务器异常，请稍后再试！\"}");
        }
    }

}
